from django.utils.safestring import mark_safe


class Pagenation(object):
    """"""
    """分页和分页标签搜索功能类"""
    """
    本类主要提供分完页的数据page_data 和 页码信息函数 Pagenation1
    “”“
    请将page_string 数据传入页面
    显示页码请在html页面最后加入
     
      <ul class="pagination">
        {{ page_string }}
     </ul>

    """
    def __init__(self,request, number_data, page_parm="page",page_size = 10,page_plus = 5):
        page = request.GET.get(page_parm, "1")
        """判断是否为中文"""
        if page.isdecimal():
            page = int(page)
        else:
            page = 1

        self.page = page
        self.page_size = page_size
        self.page_plus = page_plus

        self.page_count = number_data.count()
        self.total_page, div = divmod(self.page_count, page_size)
        if div > 0:
            self.total_page += 1
        if self.page < 1:
            self.page = 1
        if self.page > self.total_page:
            self.page = self.total_page

        self.page_start = (self.page - 1) * self.page_size
        self.page_end = self.page * self.page_size
        if number_data:
            self.page_data = number_data[self.page_start:self.page_end]
        else:
            self.page_data = None
        self.page_string = self.Pagination1()

    def Pagination1(self):
        """"""
        """页面选择显示范围"""
        if self.total_page <= 2 * self.page_plus + 1:
            start_page = 1
            end_page = self.total_page + 1
        else:
            start_page = self.page - self.page_plus
            if start_page < 1:
                start_page = 1
            end_page =self.page + self.page_plus + 1
            if end_page > self.total_page + 1:
                end_page = self.total_page + 1
        """后台批量生成页面选择标签"""
        page_str_list = []
        prev0 = '<li><a href="?page={}">首页</a></li>'.format(1)
        page_str_list.append(prev0)
        if self.page - 1:
            prev1 = '<li><a href="?page={}">上一页</a></li>'.format(self.page - 1)
        else:
            prev1 = '<li><a href="?page={}">上一页</a></li>'.format(1)
        page_str_list.append(prev1)

        for i in range(start_page, end_page):
            if i == self.page:
                ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
            else:
                ele = '<li ><a href="?page={}">{}</a></li>'.format(i, i)
            page_str_list.append(ele)

        if self.page < self.total_page:
            prev2 = '<li><a href="?page={}">下一页</a></li>'.format(self.page + 1)
        else:
            prev2 = '<li><a href="?page={}">下一页</a></li>'.format(self.total_page)
        page_str_list.append(prev2)
        prev4 = '<li><a href="?page={}">尾页</a></li>'.format(self.total_page)
        page_str_list.append(prev4)
        return mark_safe("".join(page_str_list))